/*
 * Copyright (C) 2008 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.notebad.note;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class NotesDbManager {

    public static final String KEY_ROWID = "_id";
    public static final String KEY_TITLE = "title";
    public static final String KEY_BODY = "body";
    public static final String KEY_DATE = "date";
    public static final String KEY_CATEGORY = "category";
    public static final String KEY_ADDRESS = "address";
    public static final String KEY_LATITUDE = "latitude";
    public static final String KEY_LONGITUDE = "longitude";

    private static final String TAG = "NotesDbAdapter";
    
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private static final String DATABASE_NAME = "notebadDebug";
    private static final String DATABASE_TABLE = "notes";
    private static final int DATABASE_VERSION = 5;
    
    /**
     * Database creation sql statement
     */
    private static final String DATABASE_CREATE =
            "create table " + DATABASE_TABLE + " (_id integer primary key autoincrement, "
                    + KEY_TITLE + " text not null, " + KEY_BODY + " text, " 
                    + KEY_DATE + " text not null, " + KEY_CATEGORY + " text, "+ KEY_ADDRESS 
                    + " text, " + KEY_LATITUDE + " double, " + KEY_LONGITUDE + " double);";


    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS notes");
            onCreate(db);
        }
    }

    /**
     * Constructor
     * 
     * @param Context
     */
    public NotesDbManager(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the notes database.
     */
    public NotesDbManager open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }
    
    public void close() {
        mDbHelper.close();
    }


    /**
     * Create a new note 
     */
    public long createNote(Note note) {
    	
    	// Date from now
    	Date now = new Date ();
        SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy");
        String strDate = format.format(now);
 
    	Log.d(TAG, "DATE = " + strDate);
    	
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TITLE, note.getTitle());
        initialValues.put(KEY_BODY, note.getBody());
        initialValues.put(KEY_DATE, note.getDate());
        initialValues.put(KEY_CATEGORY, note.getCategory());
        initialValues.put(KEY_ADDRESS, note.getAddress());
        initialValues.put(KEY_LATITUDE, note.getLatitude());
        initialValues.put(KEY_LONGITUDE, note.getLongitude());

        Log.i(TAG, "Creating a new note");
        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }

    /**
     * Delete the note
     */
    public boolean deleteNote(long rowId)
    {
        Log.i(TAG, "Deleting note which has " + rowId + "as id");
        return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    /**
     * Return a Cursor over the list of all notes in the database
     */
    public Cursor fetchAllNotes() {

        Cursor curs = mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_BODY, 
        		KEY_DATE, KEY_CATEGORY, KEY_ADDRESS, KEY_LATITUDE, KEY_LONGITUDE}, null, null, null, null, null);
        
        return curs;
    }

    /**
     * Return a Cursor positioned at the note that matches the given rowId
     */
    public Note fetchNote(long rowId) throws SQLException {

        Cursor mCursor =

                mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_BODY, 
                		KEY_DATE, KEY_CATEGORY, KEY_ADDRESS, KEY_LATITUDE, KEY_LONGITUDE}, 
                		KEY_ROWID + "=" + rowId, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        
        Note note = new Note(mCursor.getLong(mCursor.getColumnIndexOrThrow(KEY_ROWID)), mCursor.getString(mCursor.getColumnIndexOrThrow(KEY_DATE)), 
        		mCursor.getString(mCursor.getColumnIndexOrThrow(KEY_CATEGORY)), mCursor.getString(mCursor.getColumnIndexOrThrow(KEY_TITLE)), 
        		mCursor.getString(mCursor.getColumnIndexOrThrow(KEY_BODY)), mCursor.getDouble(mCursor.getColumnIndexOrThrow(KEY_LATITUDE)), 
        		mCursor.getDouble(mCursor.getColumnIndexOrThrow(KEY_LONGITUDE)), mCursor.getString(mCursor.getColumnIndexOrThrow(KEY_LONGITUDE)));
        
        return note;

    }

    /**
     * Update note
     * 
     */
    public boolean updateNote(Note note) {
        ContentValues args = new ContentValues();
        args.put(KEY_TITLE, note.getTitle());
        args.put(KEY_BODY, note.getBody());
        args.put(KEY_DATE, note.getDate());
        args.put(KEY_CATEGORY, note.getCategory());
        args.put(KEY_ADDRESS, note.getAddress());
        args.put(KEY_LATITUDE, note.getLatitude());
        args.put(KEY_LONGITUDE, note.getLongitude());
        
        Log.i(TAG, "Updating note which has " + note.getId() + "as id");
        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + note.getId(), null) > 0;
    }
}
